package com.github.codemperor.gateway.fitler;

import com.github.codemperor.core.logger.DefaultLogger;
import com.github.codemperor.gateway.config.BaseFilter;
import com.github.codemperor.gateway.context.FilterContext;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER;

/**
 * 请求response拦截
 */
@Component
public class ResponseFilter extends BaseFilter {
    private DefaultLogger log = DefaultLogger.logger(this.getClass());

    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        //这里比源码自己的response提前执行
        return SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        long cost = System.currentTimeMillis() - FilterContext.costMillis.get();
        log.info("[Gateway ResponseFilter] api cost: {}ms", cost);
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse res = currentContext.getResponse();
        res.setHeader("x-empr-signature", "https://empr.com");
        res.setHeader("x-empr-cost", cost + "ms");

        //清理线程中自定义的上下文内容
        clearAllCustomContext();
        return null;
    }
}
